package com.iris.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;
import java.nio.channels.FileChannel;


/**
 * 项目: thinking
 * 包名: com.iris.nio
 * 作者: victor
 * 日期: 2016年8月10日
 * 说明: BufferTest
 */
public class BufferTest {
	
	public static void main(String[] args) {
//		BufferTest.nioTest();
//		BufferTest.readTest();
		BufferTest.writeTest();
	}
	
	public static  void nioTest(){

		// 分配新的int缓冲区，参数为缓冲区容量  
        // 新缓冲区的当前位置将为零，其界限(限制位置)将为其容量。它将具有一个底层实现数组，其数组偏移量将为零。  
		IntBuffer buffer = IntBuffer.allocate(10);
		int j=0;
		for (int i = 0; i < buffer.capacity(); ++i) {  
             j= 2 * (i + 1);  
            // 将给定整数写入此缓冲区的当前位置，当前位置递增  
            buffer.put(j);
        } 
		// 重设此缓冲区，将限制设置为当前位置，然后将当前位置设置为0  
		buffer.flip();
		// 查看在当前位置和限制位置之间是否有元素  
        while (buffer.hasRemaining()) {  
            // 读取此缓冲区当前位置的整数，然后当前位置递增  
            j = buffer.get();  
            System.out.print(j + "  ");  
        } 
	}
	
	public static void readTest(){
		String path = BufferTest.class.getResource("/").getPath()+"com/iris/nio/ifyou.txt";
		System.out.println(path);
		path=path.substring(1,path.length());
		System.out.println(path);
		try {
			FileInputStream input =new FileInputStream(path);
			FileChannel channel = input.getChannel();
//			CharBuffer charb= CharBuffer.allocate(1024);
			// 创建缓冲区  
	        ByteBuffer buffer = ByteBuffer.allocate(32);  
			channel.read(buffer);
			//
			buffer.flip();
			while (buffer.remaining()>0) {  
	            byte b = buffer.get();  
	            System.out.print(((char)b));  
	        }  
	          
			input.close(); 
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	//Some bytes.
	static private final byte message[] = { 83, 111, 109, 101, 32,  
	        98, 121, 116, 101, 115, 46 };  

	public static void writeTest(){
		String path = BufferTest.class.getResource("/").getPath()+"com/iris/nio/ifyou.txt";
		System.out.println(path);
		path=path.substring(1,path.length());
		System.out.println(path);
		try {
			FileOutputStream fout = new FileOutputStream(path );  
	          
	        FileChannel fc = fout.getChannel();  
	          
	        ByteBuffer buffer = ByteBuffer.allocate( 1024 );  
	          
	        for (int i=0; i<message.length; ++i) {  
	            buffer.put( message[i] );  
	        }  
	          
	        buffer.flip();  
	          
	        fc.write( buffer );  
	          
	        fout.close();  
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
